package cn.cxyxj.study.webflux03;

import cn.cxyxj.study.webflux03.constant.Constant;
import cn.cxyxj.study.webflux03.constant.RedisKey;
import cn.cxyxj.study.webflux03.utils.RedisUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.logout.ServerLogoutSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author cxyxj
 */
@Component
public class CustomLogoutSuccessHandler implements ServerLogoutSuccessHandler {

    @Override
    public Mono<Void> onLogoutSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
        ServerWebExchange exchange = webFilterExchange.getExchange();
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().add("Content-Type", MediaType.APPLICATION_JSON_VALUE);
        //获取token
        String token = request.getHeaders().getFirst(Constant.AUTHORIZATION);
        if (StringUtils.isNotBlank(token)) {
            boolean del = RedisUtil.del(String.format(RedisKey.TOKEN, token));
            String msg = del ? "退出成功" : "退出失败";
            byte[] dataBytes = JSON.toJSONString(msg).getBytes();
            DataBuffer bodyDataBuffer = response.bufferFactory().wrap(dataBytes);
            return response.writeWith(Mono.just(bodyDataBuffer));
        } else {
            byte[] dataBytes = JSON.toJSONString("请求头信息不能为空").getBytes();
            DataBuffer bodyDataBuffer = response.bufferFactory().wrap(dataBytes);
            return response.writeWith(Mono.just(bodyDataBuffer));
        }
    }

}
